# -*- coding: utf-8 -*-
#!/usr/bin/python3

from http.server import SimpleHTTPRequestHandler
from myDbHandler import myDbHandler
import os.path
from urllib import parse
import json


class requestHandler(SimpleHTTPRequestHandler):
    __DbHandler = myDbHandler('archives.db')  # 各实例共享、唯一
    __abspath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'htmls')
    __enc = 'UTF-8'

    def __readHtmlFile(self, filename):
        enc = 'UTF-8'  # 指定返回编码
        temp = os.path.join(requestHandler.__abspath, filename)
        f = open(temp)
        c = f.read().encode(enc)
        return c

    def __set_headers(self, codeNumber=200, contentTypes=[]):  # contentType是元组列表
        self.send_response(codeNumber)
        for i in contentTypes:
            self.send_header(i[0], i[1])
        self.end_headers()
    
    # def send_dates(self, contents=None):
    #     # f1 = open('index.html')
    #     # s = f1.read()
    #     s = self.__readHtmlFile('index.html')
    #     self.__set_headers(200, [('Content-type', "text/html; charset=UTF-8"), ('Content-Length', str(len(s)))])
    #     self.wfile.write(s)

    
        

    def do_GET(self, *args, **kwargv):
        # print('OOOOpath=\n', requestHandler.__abspath)
        print("get_ok")
        print('args=', args)
        print('kwargs=', kwargv)
        print('commmand=', self.command)
        print('path=', self.path)
        print('request_version=', self.request_version)
        reqPath = self.path
        if reqPath in ['/', '/index.html', '/index']:
            s = self.__readHtmlFile('index.html')
            self.__set_headers(200, [('Content-type', "text/html; charset=UTF-8"), ('Content-Length', str(len(s)))])
            self.wfile.write(s)
        elif '.js' in reqPath:
            i = reqPath.rfind('/')
            s = self.__readHtmlFile(reqPath[i+1:])
            self.__set_headers(200, [('Content-type', "application/javascript; charset=UTF-8"), ('Content-Length', str(len(s)))])
            self.wfile.write(s)
        elif '.css' in reqPath:
            i = reqPath.rfind('/')
            s = self.__readHtmlFile(reqPath[i+1:])
            self.__set_headers(200, [('Content-type', "text/css; charset=UTF-8"), ('Content-Length', str(len(s)))])
            self.wfile.write(s)
    
    def do_POST(self, *args, **kw):
        print("post_ok")
        print('args=\n', args)
        print('kwargs=\n', kw)
        print('path=\n', self.path)
        print('request=\n', self.request)
        print('headers=\n', self.headers)
        print('requestline=\n', self.requestline)
        length = int(self.headers.__getitem__('Content-Length'))  #获取除头部后的请求参数的长度
        req_body = self.rfile.read(length).decode('utf-8')
        print('rfile=\n', req_body)
        data = parse.parse_qs(req_body)
        print('data\n', data)  # {'firstname': ['Mickey'], 'lastname': ['Mouse']}
        t = {'firstname': ['Mickey'], 'lastname': ['Mouse']}
        t = json.dumps(t).encode(requestHandler.__enc)
        self.__set_headers(200, [('Content-type', "application/json; charset=UTF-8"), ('Content-Length', str(len(t)))])
        self.wfile.write(t)
        pass
